

#include <config.h>
#include <inout.h>
#include <video.h>
#include <klib.h>

#ifdef CONF_SYS_I386
uint32 __vid_mem = 0xb8000;
#endif
uint16 __vid_offset = 0;
uint8  __vid_color = COL_BLUE;

void _vid_printc(uint16 offset, uint8 c, uint8 color){

  if (offset >= 2000) return;

  ((char *)__vid_mem)[(offset * 2) + 1] = color;
  ((char *)__vid_mem)[offset * 2] = c;

}

/**
 * This moves every line in the vid buffer up one; it destroys the line that
 * is highest.
 */
void _vid_move_lines_up(){

  int i = 1;
  for ( ; i < 25; i++){ // 25 lines of text.
    kcopy((char *) __vid_mem + (i * 160), 
	  (char *) __vid_mem + ((i-1) * 160), 160);
  }
  kzero((char *) __vid_mem + (24 * 160), 160);
  __vid_offset -= 80;

}

void _vid_offset_newline(){

  __vid_offset += 80 - (__vid_offset % 80);
  
}

void _vid_move_cursor(){

  __out_c(0x3d4, 14);
  __out_c(0x3d5, __vid_offset >> 8);
  __out_c(0x3d4, 15);
  __out_c(0x3d5, __vid_offset);


}

void vid_clear(){

  int i = 0;
  for ( ; i < 2000; i++){
    ((char*)__vid_mem)[i*2] = 0;
    ((char*)__vid_mem)[(i*2) + 1] = __vid_color;
  }
  _vid_move_cursor();

}

void vid_set_color(uint8 col){

  __vid_color = col;

}

void vid_reset(){

  __vid_color = COL_BLUE;
  __vid_offset = 0;
  _vid_move_cursor();


}

void vid_set_offset(uint16 offset){

  __vid_offset = offset;
  _vid_move_cursor();


}

void vid_printc(uint8 c){

  if (c != '\n'){
    _vid_printc(__vid_offset++, c, __vid_color);
  } else {
    _vid_offset_newline();
  }

}

void vid_printstr(char *str){

  unsigned int i = 0;
  while (str[i] != 0) vid_printc(str[i++]);
  _vid_move_cursor();

}

void vid_println(char *str){

  vid_printstr(str);
  vid_printc('\n');

}
